'''
File: createSequenceFile.py
Author: Adam Hockenberry
Description: .gb file conversion to txt file. it has several dependencies so only Adam can run at the moment
'''

import parsingGenbankFiles as pgb
import glob
import sequenceAnalysisFunctions as saf

def get_codon_and_aa_lists(genbankFileDirectory, outfileName):
     geneSequencesListOfStrings = extract_coding_sequences(genbankFileDirectory)
     codonSequencesListOfLists = [saf.split_string_into_list_of_triplets(x)[1:-1] for x in geneSequencesListOfStrings]
     aminoAcidSequences = get_amino_acid_sequences(codonSequencesListOfLists)
     write_file(codonSequencesListOfLists, aminoAcidSequences, outfileName)

def extract_coding_sequences(genbankFileDirectory):
    sequenceListGenome = []
    for infile in glob.glob(genbankFileDirectory + '*.gb'):
        sequenceListChrom = pgb.get_coding_sequences(infile)
        for sequence in sequenceListChrom:
            sequenceListGenome.append(sequence)
    print "##################################################################################"
    print "total number of sequences extracted from genome is:", len(sequenceListGenome)
    return sequenceListGenome

def get_amino_acid_sequences(codonSequencesListOfLists):
    aminoAcidSequencesGenome = []
    codonAAdict = saf.get_codon_to_AA_dict(stop=True)
    for gene in codonSequencesListOfLists:
        aminoAcidSequence = []
        for codon in gene:
            aminoAcidSequence.append(codonAAdict[codon])
        aminoAcidSequencesGenome.append(aminoAcidSequence)
    return aminoAcidSequencesGenome
            
def write_file(list1, list2, fileName):
    f = open(fileName, 'w')
    for x in range(len(list1)):
        for y in list1[x][:-1]:
            f.write(y + ',')
        f.write(list1[x][-1] + '\n')
        for y in list2[x][:-1]:
            f.write(y + ',')
        f.write(list2[x][-1] + '\n')
    f.close()
        


